#include <errno.h>
#include <iostream>
#include <pthread.h>
#include <sys/time.h>

pthread_mutex_t mutex_;// = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond_;//  = PTHREAD_COND_INITIALIZER;
void *thr_fun (void *)
{
    //pthread_mutex_lock (&mutex_);
    sleep (3);
    std::cout << "lock over" << std::endl;
}
int main ()
{
    pthread_t thr_id;
    int ret = pthread_create (&thr_id, 0, thr_fun, 0);
    std::cout << "pthread_creat ret = " << ret << " errno = " << errno << std::endl;

    ret = pthread_detach (thr_id);
    std::cout << "pthread_detach ret = " << ret << " errno = " << errno << std::endl;

    ret = pthread_join (thr_id, 0);
    std::cout << "pthread_join ret = " << ret << " errno = " << errno << std::endl;

    ret = pthread_mutex_lock (&mutex_);
    std::cout << "pthread_mutex_lock ret = " << ret << " errno = " << errno << std::endl;

    ret = pthread_mutex_trylock (&mutex_);
    std::cout << "pthread_mutex_trylock ret = " << ret << " errno = " << errno << std::endl;

    ret = pthread_cancel (thr_id);
    std::cout << "pthread_cancel ret = " << ret << " errno = " << errno << std::endl;

    int msec = 1000;
    struct timespec timeout;
    struct timeval  tp;
    ::gettimeofday (&tp, NULL);
    timeout.tv_sec   = (msec / 1000) + tp.tv_sec;
    timeout.tv_nsec  = ((msec % 1000) * 1000000) + (tp.tv_usec * 1000);
    while (timeout.tv_nsec >= 1000000000)
    {
	timeout.tv_nsec -= 1000000000;
	timeout.tv_sec++;
    }

    ret = pthread_cond_timedwait (&cond_, &mutex_, &timeout);
    std::cout << "pthread_cond_timedwait ret = " << ret << " errno = " << errno << std::endl;

    ret = pthread_cond_wait (&cond_, &mutex_);
    std::cout << "pthread_cond_wait ret = " << ret << " errno = " << errno << std::endl;

    return 0;
}
